import cgi
import urllib
import urllib2
import sys
import feedparser
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api.labs import taskqueue

## Modelos
class Feed(db.Model):
	url = db.StringProperty()
	titulo = db.StringProperty()
	ultimaActualizacion = db.DateTimeProperty()
	
class User(db.Model):
	mail = db.StringProperty()
	nombre = db.StringProperty()

class UserFeed(db.Model):
	#user = db.StringProperty()
	#feed = db.StringProperty()
	user = db.ReferenceProperty(User)
	feed = db.ReferenceProperty(Feed)
	##cambiar por db.ReferenceProperty(

class Post(db.Model):
	url = db.StringProperty()
	titulo = db.StringProperty()
	cuerpo = db.TextProperty() 
	feed = db.ReferenceProperty(Feed)
	enviado = db.BooleanProperty(default = False)

## Enviadores
class enviarMailCada10(webapp.RequestHandler):
	def get(self):
		self.response.out.write("Holo!")
	
##Para obtener los posts, se deberia ejecutar con cron, llama a getPosts para todos los feeds.
class revisar(webapp.RequestHandler):
  def get(self):
	
	self.response.out.write("""
      <html>
	  <head>
	  <title>ReaderToMail - Google Reader in your mail</title>
	    </head>
        <body>
          <h1>Revisando.</h1> <br/>
        """)
		
	for item in Feed.all():
		self.response.out.write(item.url+"<br/>")
		taskqueue.add(url='/getPosts', params={'url': item.url})

	self.response.out.write("""</body>
      </html>""")

	  

class getPosts(webapp.RequestHandler):
	def post(self):
		url = self.request.get('url')
		pagina = Feed.all()
		pagina.filter("url =",url)
		deDonde = pagina[0]
		
		feed = feedparser.parse(url)
		for i in feed["items"]:
			titulo = i[ "title" ]
			existe = Post.all()
			existe.filter("title =", titulo)
			if existe.count()==0:
				link = i[ "link" ]
				fecha = i[ "date" ]
				self.response.out.write(fecha+"<br/>")
				#por si no tiene posts... que es raro
				try:
					cuerpo = i.content[0].value
				except Exception, e:
					return
				poner = Post()
				poner.url = link
				self.response.out.write(link+"<br/>")
				poner.titulo = titulo
				self.response.out.write(titulo+"<br/>")
				poner.cuerpo = cuerpo
				self.response.out.write(cuerpo+"<br/>")
				poner.feed = deDonde
				self.response.out.write(deDonde.url+"<br/><br/>")
				poner.enviado = False
				poner.put()
			deDonde.ultimaActualizacion = datetime.now()
			deDonde.put()
		
		
##Sender Oficial
class sendPosts(webapp.RequestHandler):
	def get(self):
		self.response.out.write("""
      <html>
	  <head>
	  <title>ReaderToMail - Google Reader in your mail</title>
	  
	  </head>
        <body>""")
		
		self.response.out.write("<h1>Enviando Posts</h1><br/>")

		
		for u in User.all():
			self.response.out.write(u.mail+"<br/>")
			para = ""+u.mail+" <"+u.mail+">"
			relacion = UserFeed.all()
			relacion.filter("user =", u)
			titulo = "[Reader to Mail] Cantidad: "
			cuerpo = ""
			contador = 0
			todos = Post.all()
			todos.filter("enviado =", False)
			enviados = []
			
			##obtengo el arreglo de feeds que sirven
			feedsirven = []
			for r in relacion:
				feedsirven.append(r.feed)
			## se cae aca, pensar forma mas inteligente...
			for post in todos:
				if post.feed in feedsirven:
					contador=contador+1
					cuerpo+=post.titulo+"<br/><br/>"
					cuerpo+=post.cuerpo+"<br/><br/><br/><br/><br/>"
					enviados.append(post)
			titulo+=str(contador)
			#mail.send_mail(sender="Reader to Mail <greadertomail@gmail.com>", to=para, subject=titulo, body=cuerpo)
			self.response.out.write(str(contador)+" Posts enviados a: "+u.mail)
			#posts enviados
					
			
		self.response.out.write(""""</body>
      </html>""")
	

##Helpers	
class eliminarPosts(webapp.RequestHandler):
	def get(self):
		lista = Post.all()
		for i in lista:
			i.delete()
		self.response.out.write("Posts eliminados")

class prueba(webapp.RequestHandler):
	def get(self):
		r = UserFeed.all()
		for i in r:
			self.response.out.write(i.feed.url)
					
	
## Paginas
class MainPage(webapp.RequestHandler):
  def get(self):
	self.response.out.write("""
      <html>
	  <head>
	  <title>ReaderToMail - Google Reader in your mail</title>
	  
	  </head>
        <body>
          <form action="/acceder" method="post">
            <div>Email: <input type="text" name="mail"></input></div>
			<div>Password: <input type="password" name="passwd"></input></div>
            <div><input type="submit" value="Acceder"></div>
          </form>
        </body>
      </html>""")
  


##Obntener los feeds de un usuario y registrarlo
class getFeeds(webapp.RequestHandler):
	def post(self):
		username = self.request.get('mail')
		password = self.request.get('passwd')
		auth_url = 'https://www.google.com/accounts/ClientLogin'
		auth_req_data = urllib.urlencode({'Email': username, 'Passwd': password, 'service': 'reader'})
		auth_req = urllib2.Request(auth_url, data=auth_req_data)
		auth_resp = urllib2.urlopen(auth_req)
		auth_resp_content = auth_resp.read()
		auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x)
		auth_token = auth_resp_dict["Auth"]
		# Create a cookie in the header using the SID 
		header = {}
		header['Authorization'] = 'GoogleLogin auth=%s' % auth_token
		reader_base_url = 'http://www.google.com/reader/api/0/subscription/list'
		reader_url = reader_base_url
		reader_req = urllib2.Request(reader_url, None, header)
		reader_resp = urllib2.urlopen(reader_req)
		reader_resp_content = reader_resp.read()
		resultado = reader_resp_content
		res2 = resultado.split(">")
		final = []
		for la in res2:
			final.extend(la.split("<"))
		retorno = []
		for la in final:
			if "http" in la:
				retorno.append(la)
		retorno2 = []
		
		aEliminar = UserFeed.all()
		aEliminar.filter("user.mail =", username)
		for eliminado in aEliminar:
			eliminado.delete()
		
		for la in retorno:
			if la.startswith('feed/'):
				retorno2.append(la[5:])
				
		self.response.out.write("""
      <html>
	  <head>
	  <title>Your Feeds</title>
	  <link rel="icon" type="image/png" href="img/favicon.ico">
	  </head>
        <body>""")
		self.response.out.write("<H1>Te Has suscrito a</H1></br><h2>Tus Feeds:</h2><br/><br/>")
		usuario = User.all()
		usuario.filter("mail =", username)
		if usuario.count()==0:
			u2 = User()
			u2.mail = username
			u2.put()
			#agregar nombre
		
		for imprime in retorno2:
			fid = Feed.all()
			fid.filter("url =", imprime)
			if fid.count()==0:
				f = Feed()
				f.url=imprime
				# Falta poner titulo y ver lo del ID.
				f.titulo="prueba"
				f.put()
			r = UserFeed.all()
			usuario = User.all()
			usuario.filter("mail =", username)
			fi = Feed.all()
			fi.filter("url =", imprime)
			
			r.filter("user =", usuario[0])
			r.filter("feed =", fi[0])
			if r.count()==0:
				r2 = UserFeed()
				r2.user = usuario[0]
				r2.feed = fi[0]
				r2.put()
			
			self.response.out.write(imprime)
			self.response.out.write("<br/>")
		self.response.out.write("""</body>
      </html>""")
		
	
	

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/acceder', getFeeds),
									  ('/mail10', enviarMailCada10),
									  ('/revisar', revisar),
									  ('/getPosts', getPosts),
									  ('/eliminarPosts', eliminarPosts),
									  ('/sendPosts', sendPosts),
									  ('/prueba', prueba)],
                                     debug=True)


def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
  




